iT邦幫忙

2025 iThome 鐵人賽

DAY 21
1
AI & Data

從0開始的MLFLOW應用搭建系列 第 21

Day 21 – FastAPI 安裝與架構概覽

  • 分享至 

  • xImage
  •  

🎯 目標

今天的重點是:

  1. 認識 FastAPI 的運作架構。
  2. 在現有 Docker 專案中新增 FastAPI 服務。
  3. 建立第一個 /health 測試端點。
  4. 預告明天會把它擴充成 /recommend 推薦 API。

🔍 背景

在前 20 天,我們完成了 MLflow 模型的:

  • 建立、追蹤、註冊、部署與自動化 retrain。

但這些模型目前只存在於 MLflow server 裡。
要讓「應用層」或「前端 UI」使用推薦模型,
我們需要一個穩定、乾淨、可擴充的 API 層 ——
這正是 FastAPI 的任務。


🧱 FastAPI 架構概念

FastAPI 是 Python 最快的 Web Framework 之一,
使用 Pydantic 驗證輸入,並自動生成 Swagger UI

它的角色是:

Client (使用者 / Streamlit)
        │
        ▼
   [FastAPI Server]
        │
        └── /recommend → 呼叫 MLflow 模型

後續我們會做到:

  • /recommend:從模型輸出推薦清單。

⚙️ 1. 新增 FastAPI Docker Service

在你的 docker-compose.yml 中新增以下段落:

  fastapi:
    build:
      context: .
      dockerfile: docker/Dockerfile.fastapi
    container_name: fastapi
    ports:
      - "8000:8000"
    volumes:
      - ./src/api:/usr/mlflow/src/api
    working_dir: /usr/mlflow/src/api
    command: uvicorn main:app --host 0.0.0.0 --port 8000 --reload
    networks:
      - mlops-net

🐳 2. 建立 FastAPI Dockerfile

📂 docker/Dockerfile.fastapi

FROM python:3.10-slim

WORKDIR /usr/mlflow

COPY docker/requirements-dev.txt .
RUN pip install --no-cache-dir -r requirements-dev.txt

# 安裝 FastAPI 與 Uvicorn
RUN pip install fastapi==0.111.0 uvicorn==0.30.1

EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

🧩 3. 建立 FastAPI 主程式

📂 src/api/main.py

from fastapi import FastAPI

app = FastAPI(
    title="Anime Recommender API",
    description="FastAPI + MLflow 推薦系統",
    version="1.0.0"
)

@app.get("/health")
def health_check():
    return {"status": "ok", "message": "FastAPI is running 🚀"}

▶️ 4. 啟動服務

執行:

docker compose up -d fastapi

查看容器:

docker ps

確認有一個 fastapi container 在跑。
接著打開瀏覽器:
👉 http://127.0.0.1:8000/docs

你會看到自動產生的 Swagger UI:
https://ithelp.ithome.com.tw/upload/images/20251005/201786263OW091n6xj.png


🔗 5. 驗證 API

在內部網路中,我們可以使用以下語法確認API,於是我們可以回到jupyter環境執行:

curl http://fastapi:8000/health

回傳:

{
  "status": "ok",
  "message": "FastAPI is running 🚀"
}

https://ithelp.ithome.com.tw/upload/images/20251005/20178626iGG1P011bi.png

代表你的 FastAPI 環境架構成功!


🧭 架構總覽

Docker Compose
│
├── mlflow       → 模型管理與註冊
├── postgres     → MLflow backend
├── python-dev   → Notebook 開發環境
└── fastapi      → 模型服務層 (API)

FastAPI 是整個系統的「應用層」,
之後會與 MLflow registry 的模型互動。


✅ 重點總結

  • FastAPI 是本系統的「模型服務 API 層」。
  • 透過 Docker Compose 建立新服務容器。
  • 成功啟動 /health 端點,驗證 API 架構。
  • 下一步(Day 22)將新增 /recommend
    從 MLflow Model Registry 載入推薦模型並實際產生推薦結果。

💡 延伸思考

在企業實作中,FastAPI 通常還會:

  • 整合 JWT Token 或 OAuth 登入保護 API。
  • 配合 Gunicorn + Nginx 作為生產環境部署。
  • 搭配 Prometheus / Grafana 做 API 監控。

但在這個 30 天系列中,我們保持「最小可行」策略,
讓你先能跑通完整 MLOps + API 流程,再逐步進階。


上一篇
Day 20 – MLflow 全流程總整理
下一篇
Day 22 – 建立推薦 API /recommend
系列文
從0開始的MLFLOW應用搭建23
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言